<?php
// +----------------------------------------------------------------------
// | B5LaravelCMF
// +----------------------------------------------------------------------
// | Author: 李恒 <357145480@qq.com>
// +----------------------------------------------------------------------
namespace App\Services;

use App\Models\Menu;
use App\Validates\MenuValidate;


/**
 * 菜单管理
 * Class MenuService
 * @package App\Services
 */
class MenuService extends BaseService
{
    public function __construct(bool $loadValidate = true)
    {
        $this->setModel(new Menu());
        $loadValidate && $this->setValidate(new MenuValidate());
    }

    public function getList($all = false)
    {

        return parent::getList($all,[],[['parent_id','asc'],['listsort','asc'],['id','asc']]); // TODO: Change the autogenerated stub
    }

    /**
     * 菜单类型
     * @return array
     */
    public function typeList()
    {
        return ['M' => '目录', 'C' => '菜单', 'F' => '按钮'];
    }

    /**
     * 获取菜单信息时返回父菜单名称
     * @param $id
     * @param bool $isArray
     * @return mixed
     */
    public function info($id, bool $isArray = true)
    {
        $info = parent::info($id, $isArray);
        if ($info) {
            $info['parent_name'] = '主目录';
            if ($info['parent_id'] > 0) {
                $parentInfo = $this->model->info($info['parent_id'], true);
                if ($parentInfo) {
                    $info['parent_name'] = $parentInfo['name'];
                } else {
                    $info['parent_name'] = '不存在';
                }
            }
        }
        return $info;
    }

    /**
     * 删除菜单时，若有子菜单则无法删除
     * @return array
     */
    public function drop()
    {
        $ids = request()->input('ids');
        if ($ids) {
            if (is_array($ids)) {
                $idArr = $ids;
            } else {
                $ids = trim($ids, ',');
                $idArr = explode(',', $ids);
            }
            foreach ($idArr as $id) {
                $id = intval($id);
                if ($id) {
                    $hasChild = parent::info([['parent_id', '=', $id]], true);
                    if ($hasChild) {
                        return message('不能删除含有子菜单的菜单', false);
                    }
                }
            }
        }
        return parent::drop(); // TODO: Change the autogenerated stub
    }

    /**
     * 选择父级菜单的菜单树数据
     * @return array
     */
    public function getTree()
    {
        $list = $this->getAll([], ['id', 'parent_id', 'name'], [], '', [['parent_id', 'asc'], ['listsort', 'asc']]);
        $root = request()->input('root', 1);
        if ($root) {
            $first = [
                'id' => 0,
                'parent_id' => -1,
                'name' => '主目录'
            ];
            if ($list) {
                array_unshift($list, $first);
            }
        }
        return message('操作成功', true, $list);
    }


    /**
     * 根据用户ID获取后台展示的菜单
     * @param $adminId
     * @return string
     */
    public function getMenuList($adminId)
    {
        $menuHtml='';
        $menuList = [];
        if ($adminId) {
            if($adminId==1){
                $menuList = (new MenuService())->getAll([['type', '<>', 'F'], ['status', '=', 1]], ['id', 'type', 'name', 'url', 'parent_id', 'icon', 'is_refresh','target'], [], '', [['parent_id', 'asc'], ['listsort', 'asc'], ['id', 'asc']]);
            }else{
                //获取管理员分组
                $roleList = (new AdminRoleService())->getListByAdmin($adminId, false, false);

                //获取分组菜单权限ID
                $menuIdList = (new RoleMenuService())->getRoleMenuList($roleList);
                if ($menuIdList) {
                    //获取菜单
                    $menuList = (new MenuService())->getAll([['id', 'in', $menuIdList], ['type', '<>', 'F'], ['status', '=', 1]], ['id', 'type', 'name', 'url', 'parent_id', 'icon', 'is_refresh','target'], [], '', [['parent_id', 'asc'], ['listsort', 'asc'], ['id', 'asc']]);
                }
            }
        }
        if($menuList){
            $menuTree=$this->getMenuTree($menuList);
            if($menuTree){
                $menuHtml=$this->menuToHtml($menuTree);
            }
        }
        return $menuHtml;
    }

    /**
     * 根据登录session获取菜单
     * @return string
     */
    public function getMenuListByLogin(){
        $menuHtml='';
        $menuList=[];
        $adminId=adminLoginInfo('info.id');
        if($adminId){
            if($adminId==1){
                $menuList = (new MenuService())->getAll([['type', '<>', 'F'], ['status', '=', 1]], ['id', 'type', 'name', 'url', 'parent_id', 'icon', 'is_refresh','target'], [], '', [['parent_id', 'asc'], ['listsort', 'asc'], ['id', 'asc']]);
            }else {
                $menuIdList = adminLoginInfo('menu');
                if ($menuIdList) {
                    //获取菜单
                    $menuList = (new MenuService())->getAll([['id', 'in', $menuIdList], ['type', '<>', 'F'], ['status', '=', 1]], ['id', 'type', 'name', 'url', 'parent_id', 'icon', 'is_refresh', 'target'], [], '', [['parent_id', 'asc'], ['listsort', 'asc'], ['id', 'asc']]);
                }
            }
        }
        if($menuList){
            $menuTree=$this->getMenuTree($menuList);
            if($menuTree){
                $menuHtml=$this->menuToHtml($menuTree);
            }
        }
        return $menuHtml;
    }
    /**
     * 将菜单转为数形无限极
     * @param $list
     * @param int $pid
     * @param int $deep
     * @return array
     */
    public function getMenuTree($list, $pid = 0, $deep = 0)
    {
        $tree = [];
        foreach ($list as $key => $row) {
            if ($row['parent_id'] == $pid) {
                $row['deep'] = $deep;
                unset($list[$key]);
                $row['child'] = $this->getMenuTree($list, $row['id'], $deep + 1);
                $tree[] = $row;
            }
        }
        return $tree;
    }
    /**
     * 将菜单树形转为html
     * @param $menus
     * @param int $deep
     * @return string
     */
    public function menuToHtml($menus,$deep=0)
    {
        $html = '';
        if (is_array($menus)) {
            foreach ($menus as $t) {
                if($t['parent_id']==$deep){
                    if ($t['type'] == 'C') {
                        if($t['parent_id']==0){
                            $html .= '<li><a class="'.($t['target']=='1'?'menuBlank':'menuItem').'" href="'.$t['url'].'" data-refresh="'.($t['is_refresh']?'true':'false').'">'.($t['icon']?'<i class="'.$t['icon'].'"></i>':'').' <span class="nav-label">'.$t['name'].'</span></a></li>';
                        }else{
                            $html .= '<li><a class="'.($t['target']=='1'?'menuBlank':'menuItem').'" href="'.$t['url'].'" data-refresh="'.($t['is_refresh']?'true':'false').'">'.$t['name'].'</a></li>';
                        }

                    } else {
                        if($t['child'] && $deep<2){
                            $html .= '<li><a href="javascript:;">'.($t['icon']?'<i class="'.$t['icon'].'"></i>':'').' <span class="nav-label">'.$t['name'].'</span><span class="fa arrow"></span></a>';
                            $html.='<ul class="nav '.($deep==0?'nav-second-level':'nav-third-level').'">';
                            $html .= $this->menuToHtml($t['child'],$t['id']);
                            $html = $html . "</ul></li>";
                        }
                    }
                }

            }
        }
        return $html ;
    }

}
